package com.slz.crm.common.excellistener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.slz.crm.common.exiception.BaseException;
import com.slz.crm.common.exiception.ServiceException;
import com.slz.crm.common.untils.BaseUnit;
import com.slz.crm.common.untils.ValidationUtils;
import com.slz.crm.pojo.excel.CustomerCompanyExcel;
import com.slz.crm.pojo.entity.CustomerCompanyEntity;
import com.slz.crm.pojo.entity.UserEntity;
import com.slz.crm.server.constant.MessageConstant;
import com.slz.crm.server.mapper.UserMapper;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class CustomerCompanyListener implements ReadListener<CustomerCompanyExcel> {

    private final List<CustomerCompanyEntity> dataList = new ArrayList<>();
    private final Long ownerId;
    private final UserMapper userMapper;

    public CustomerCompanyListener(UserMapper userMapper) {
        this.ownerId = BaseUnit.getCurrentId();
        this.userMapper = userMapper;
    }

    @Override
    public void invoke(CustomerCompanyExcel customerCompanyExcel, AnalysisContext analysisContext) {


        //转为Entity类型
        CustomerCompanyEntity customerCompany = new CustomerCompanyEntity();
        BeanUtils.copyProperties(customerCompanyExcel, customerCompany);

        if(customerCompany.getCreatorId() == null){
            customerCompany.setCreatorId(ownerId);
        }

        //检查是负责人是否存在
        if(customerCompany.getCreatorId() != null){
            UserEntity userEntity = userMapper.selectById(customerCompany.getCreatorId());
            if(userEntity == null){
                throw new BaseException(String.format(MessageConstant.EXCEL_IS_ERROR, dataList.size() + 2));
            }
        }

        //检查格式
        if(!ValidationUtils.isValidMobile(customerCompany.getPhone()) || customerCompany.getCompanyName() == null){
            throw new BaseException(String.format(MessageConstant.EXCEL_IS_ERROR, dataList.size() + 2));
        }

        dataList.add(customerCompany);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public List<CustomerCompanyEntity> getData(){
        return this.dataList;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        // 处理读取异常（如数据格式错误等）
        if (exception instanceof IllegalArgumentException) {
            throw new BaseException(MessageConstant.FILE_IS_EMPTY);
        }else {
            throw new ServiceException(exception.getMessage());
        }
    }

}
